package com.app.daymicdatasource.datasource;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public enum DatasourceScheduler {
    Instance;
    private AtomicInteger cacheTaskNumber = new AtomicInteger(1);
    private ScheduledExecutorService scheduledExecutorService;
    DatasourceScheduler(){
        create();
    }

    /**
     * 创建一个核心线程数为10的线程池
     */
    public void create(){
        this.shutdown();
        this.scheduledExecutorService = new ScheduledThreadPoolExecutor(10, r -> new Thread(r, String.format("Datasource-Release-Task-%s", cacheTaskNumber.getAndIncrement())));
    }
    private void shutdown() {
        if (null != this.scheduledExecutorService) {
            this.scheduledExecutorService.shutdown();
        }
    }

    /**
     * 定时执行
     * @param task
     * @param delay
     */
    public void schedule(Runnable task,long delay){
        this.scheduledExecutorService.scheduleAtFixedRate(task, delay, delay, TimeUnit.MILLISECONDS);
    }

}
